package br.com.merks.controller.component;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.mortbay.log.Log;

import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.SessionScoped;
import br.com.merks.controller.MarketController;
import br.com.merks.model.Market;
import br.com.merks.model.MarketAnswer;

@Component
@SessionScoped
public class MarketSessionHandler {
	public static final Logger logger = Logger.getLogger(MarketSessionHandler.class);
	private HttpSession session;
    public MarketSessionHandler(HttpSession session) {
        this.session = session;
    }
    public void setMarket(Market question) {
    	this.session.setAttribute("market", question);
    }
    public void setMarketAnswers(List<MarketAnswer> questionAnswers) {
    	this.session.setAttribute("marketAnswers", questionAnswers);
    }
    
    public void addAnswer(MarketAnswer questionAnswer) {
    	List<MarketAnswer> qs = getMarketAnswers();
    	if (qs==null) qs = new ArrayList<MarketAnswer>();
    	questionAnswer.setTempId(getIncrement());
     	qs.add(questionAnswer);
    	this.setMarketAnswers(qs);
    }
    
    public synchronized void  dropAnswer(MarketAnswer questionAnswer) {
    	List<MarketAnswer> qs = getMarketAnswers();
    	if (qs==null) {
    		return;
    	} else {
    		MarketAnswer drop = null;
    		for (MarketAnswer qa : qs) {
    			logger.debug("MarketAnswer " + qa.getTempId() + " " + qa.getAnswer());
    			if (qa.getTempId().equals(questionAnswer.getTempId())) {
    				logger.debug("Removing market answer " + qa.getTempId());
    				drop = qa;
    				
    			}
    		}
    		qs.remove(drop);
    	}
    	logger.debug("Total question answers " + qs.size());
    	this.setMarketAnswers(qs);
    }
    
  
    public Long getIncrement() {
    	Object o = this.session.getAttribute("increment");
    	long actual = 0;
    	if (o!=null) actual = (Long) o ;
    	actual = actual + 1;
    	this.session.setAttribute("increment",actual);
    	return actual;
    }
    public Market getMarket() {
    	return (Market) this.session.getAttribute("market");
    }
    public List<MarketAnswer> getMarketAnswers() {
    	return (List<MarketAnswer>) this.session.getAttribute("marketAnswers");
    }
    
    public void clean() {
    	this.setMarket(null);
    	this.setMarketAnswers(null);
    }
}
